<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- search -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryData.query" clearable @clear="getUserLise">
            <el-button slot="append" icon="el-icon-search" @click="getUserLise"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格结构 -->
      <el-table :data="users" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column  prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch @change="swichChange(scope.row)" v-model="scope.row.mg_state" active-color="#409eff" inactive-color="#dcdfe6"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
             <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row.id)"></el-button>
             <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row.id)"></el-button>
             <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
               <el-button type="warning" icon="el-icon-setting" size="mini" @click="showDbDialogVisible(scope.row)"></el-button>
             </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="分配角色" :visible.sync="dbDialogVisible" width="50%">
        <div class="text">
          <p>当前用户: {{userInfo.username}}</p>
          <p>当前角色: {{userInfo.role_name}}</p>
          <div>分配新角色:
            <el-select v-model="selectValue" placeholder="请选择">
              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
            </el-select>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dbDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subSetRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
        <el-form :model="addUserForm" ref="addUserRef" class="demo-ruleForm" label-width="80px"  :rules="addUserFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAdd">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%" @close="resetEditForm">
        <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱"  prop="email">
          <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机"  prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEdit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'user',
  data () {
    const checkEmail = (rule, val, fn) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (reg.test(val)) {
        fn()
      } else {
        fn(new Error('邮箱格式不正确'))
      }
    }
    const checkmobile = (rule, val, fn) => {
      const reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (reg.test(val)) {
        fn()
      } else {
        fn(new Error('手机号码格式不正确'))
      }
    }
    return {
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      users: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addUserForm: {
        username: 'xibJane',
        password: 'xtq1099326218',
        email: '1099326218@qq.com',
        mobile: '18166666666'
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 77, message: '长度在 2 到 77 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'string', required: true, message: '请选择日期', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { type: 'string', required: true, message: '请选择时间', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      dbDialogVisible: false,
      userInfo: {},
      rolesList: {},
      selectValue: ''
    }
  },

  created () {
    // axios请求 获取用户列表
    this.getUserLise()
  },

  methods: {
    // axios请求 获取用户列表
    async getUserLise () {
      const { data: res } = await this.$axios.get('users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.total = res.data.total
      this.users = res.data.users
    },
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUserLise()
    },
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUserLise()
    },
    async swichChange (userInfo) {
      const { data: res } = await this.$axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    resetAddForm () {
      this.$refs.addUserRef.resetFields()
    },
    submitAdd () {
      this.$refs.addUserRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getUserLise()
      })
    },
    async editUser (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$axios.get('users/' + id)
      this.editForm = res.data
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    submitEdit () {
      this.$refs.editFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          model: this.editForm.model
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.message)
        this.editDialogVisible = false
        this.getUserLise()
      })
    },
    delUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message({
          type: 'success',
          message: '删除成功!'
        },
        this.getUserLise()
        )
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async showDbDialogVisible (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      this.dbDialogVisible = true
    },
    async subSetRole () {
      if (!this.selectValue) return this.$message.error('请选择角色')
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectValue
      })
      if (res.meta.status !== 200) {
        this.$message.success('分配成功')
        this.getUserLise()
        this.dbDialogVisible = false
      }
    }
  }
}
</script>

<style scoped lang='less'>
  .el-pagination {
    margin-top: 15px;
  }
  .text p {
    margin-top: 10px;
  }
  .text div {
    margin-top: 5px;
  }
</style>
